'use strict';

var Koa=require('koa');

var router=require('koa-router')();

const nunjucks = require('nunjucks');

var app=new Koa();

function createEnv(path, opts) {
    var
        autoescape = opts.autoescape === undefined ? true : opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader('views', {
                noCache: noCache,
                watch: watch,
            }), {
                autoescape: autoescape,
                throwOnUndefined: throwOnUndefined
            });
    if (opts.filters) {
        for (var f in opts.filters) {
            env.addFilter(f, opts.filters[f]);
        }
    }
    return env;
}

var env = createEnv('views', {
    watch: true,
    filters: {
        hex: function (n) {
            return '0x' + n.toString(16);
        }
    }
});



app.use(async (ctx,next)=>{
    console.log(`处理 ${ctx.req.method} ${ctx.req.url}...`);
    await next();
});

router.get('/',async (ctx,next)=>{
    ctx.response.body='中华人民共和国';
});

router.get('/hello/:name',async (ctx,next)=>{
    var name=ctx.params.name;
    ctx.response.body=`你好呀，${name}`;
});

app.use(router.routes());

app.listen(3000);

console.log('程序运行在3000端口');